package concurrency;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author Mr.Sun
 * @date 2022年09月04日 20:11
 *
 * 装饰花园：演示终结任务
 * <p>
 *     在这个仿真程序中，花园委员会希望了解每天通过多个大门进入公园的总人数。
 *     每个大门都有一个十字转门或者某种其他形式的计数器，并且任何一个十字转门的计数值递增时，就表示公园中的总人数的共享计数值也会递增。
 * </p>
 */
public class OrnamentalGarden {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            exec.execute(new Entrance(i));
        }
        TimeUnit.SECONDS.sleep(3);
        Entrance.cancel();
        exec.shutdown();
        if (!exec.awaitTermination(250, TimeUnit.MILLISECONDS)) {
            System.out.println("某些任务未被终止！");
        }
        System.out.println("Total: " + Entrance.getTotalCount());
        System.out.println("Sum of Entrances: " + Entrance.sumEntrances());
    }
}

class Count {
    private int count = 0;
    private Random ran = new Random(47);

    // 删除synchronized关键字以查看计数失败
    public synchronized int increment() {
        int temp = count;
        if (ran.nextBoolean()) {
            Thread.yield();
        }
        return count = ++temp;
    }

    public synchronized int value () {
        return count;
    }
}

class Entrance implements Runnable {

    private static Count count = new Count();
    private static List<Entrance> entranceList = new ArrayList<>();
    private int number = 0;
    private final int id;
    private static volatile boolean canceled = false;

    /**
     * 原子操作
     */
    public static void cancel() {
        canceled = true;
    }

    public Entrance(int id) {
        this.id = id;
        // 将此任务保留在列表中, 也防止无用任务被垃圾回收
        entranceList.add(this);
    }

    @Override
    public void run() {
        while (! canceled) {
            synchronized (this) {
                ++ number;
            }
            System.out.println(this + " Total: " + count.increment());
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                System.out.println("sleep interrupted");
            }
        }
        System.out.println("Stopping " + this);
    }

    public synchronized int getValue() { return number; }

    @Override
    public String toString() {
        return "Entrance " + id + ": " + getValue();
    }

    public static int getTotalCount() {
        return count.value();
    }

    public static int sumEntrances() {
        int sum = 0;
        for(Entrance entrance : entranceList)
            sum += entrance.getValue();
        return sum;
    }
}
